import { NodeProps } from '@/components/workflow/types'
import { useWorkFlowStore } from '@/store/workflowStore'
import { CaretRightOutlined } from '@ant-design/icons'
import type { CollapseProps } from 'antd'
import { Collapse, theme } from 'antd'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import CollapseNodeComponent from '../components/CollapseNodeComponent'
import RunDrawer from '../components/RunDrawer'
import InputCont from '../llm/component/InputCont'
import LimModeCont from '../llm/component/LimModeCont'
// import { ToolExportationCont } from '../tool/components/ToolExportationCont'
import ExportationCont from '../llm/component/ExportationCont'
import IntentInputCont from './components/IntentInputCont'
import IntentRecognizeCont from './components/IntentRecognizeCont'
import { getIntentDefaultParams } from './default'
import './index.less'

/* 意图识别Panel显示 */
const IntentPanel: FC<NodeProps> = ({ id, data }: any) => {
  const { flowVariables, setFlowVariables } = useWorkFlowStore()

  const { token } = theme.useToken()
  const panelStyle: React.CSSProperties = {
    marginBottom: 24,
    background: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    border: 'none'
  }

  const createCollapseItem = (key: string, label: JSX.Element, children: JSX.Element) => ({
    key,
    label,
    children,
    style: panelStyle
  })

  const [info, setInfo] = useState({ ...getIntentDefaultParams() }) as any

  const getSourceOptions = info => {
    return info.inputList
      ? info.inputList.filter(input => input.variable).map(input => ({ value: input.variable, label: input.variable }))
      : []
  }

  const [sourceOptions, setSourceOptions] = useState<{ value: string; label: string }[]>(getSourceOptions(info))
  const editData = e => {
    const obj = { ...info, ...e }
    setInfo(obj)
    setFlowVariables(id, data.title, obj)
    setSourceOptions(getSourceOptions(obj))
  }

  // 溯源信息处理后再加载页面内容
  const [loadContent, setLoadContent] = useState(false)
  useEffect(() => {
    setLoadContent(true)
  }, [sourceOptions])

  /* 模型 */
  const ModeItems: CollapseProps['items'] = [
    createCollapseItem(
      '1',
      <CollapseNodeComponent title="模型"></CollapseNodeComponent>,
      // <IntentModeCont info={info} editData={editData} />
      <LimModeCont info={info} editData={editData} />
    )
  ]

  /* 输入 */
  const InputItems: CollapseProps['items'] = [
    createCollapseItem(
      '6',
      <CollapseNodeComponent title="输入" tooltipText="输入需要做意图识别判断的参数"></CollapseNodeComponent>,
      <>{loadContent && <IntentInputCont info={info} editData={editData} />}</>
    )
  ]

  /* 意图匹配 */
  const RecognizeItems: CollapseProps['items'] = [
    createCollapseItem(
      '7',
      <CollapseNodeComponent title="意图匹配" tooltipText="用于与用户输入匹配的意图选项"></CollapseNodeComponent>,
      <>{loadContent && <IntentRecognizeCont info={info} sourceOptions={sourceOptions} editData={editData} />}</>
    )
  ]

  /* 高级设置 */
  const SettingItems: CollapseProps['items'] = [
    createCollapseItem(
      // 默认不展开 id不需要同步
      '2+advanced',
      <CollapseNodeComponent title="高级设置" tooltipText="输入内容将会被追加到系统提示词中"></CollapseNodeComponent>,
      <>
        {loadContent && (
          <InputCont
            info={info}
            sourceOptions={sourceOptions}
            editData={editData}
            placeholder="支持额外的系统提示词，如对意图选项提供更详细的例子以增强用户输入与意图匹配的成功率。"
            errorShow="内容不可为空"
            // type="noRequired" 不判断空
            type="noRequired"
          ></InputCont>
        )}
      </>
    )
  ]

  /* 输出 */
  const ExportationItems: CollapseProps['items'] = [
    createCollapseItem(
      '5',
      <CollapseNodeComponent
        title="输出"
        tooltipText="匹配的意图选项将作为变量被其他节点引用。"
      ></CollapseNodeComponent>,
      // <ToolExportationCont info={info} editData={editData} />
      <ExportationCont info={info} editData={editData} />
    )
  ]

  useEffect(() => {
    if (flowVariables && flowVariables[data.id]) {
      const obj = {
        ...info,
        ...flowVariables[data.id]
      }
      setInfo(obj)
      /* 单节点运行弹窗 */
      if (flowVariables[data.id].runDrwaerHid === 1) {
        setrunDrawerHid(true)
      }
      setSourceOptions(getSourceOptions(obj))
    }
  }, [flowVariables])

  /* 运行弹窗 */
  const [runDrawerHid, setrunDrawerHid] = useState(false)

  /*  Collapse = list */
  const collapseItems = [
    { key: '1', title: '模型', items: ModeItems },
    { key: '6', title: '输入', items: InputItems },
    { key: '7', title: '意图匹配', items: RecognizeItems },
    { key: '2', title: '高级设置', items: SettingItems },
    { key: '5', title: '输出', items: ExportationItems }
  ]
  const collapseProps = {
    bordered: false,
    expandIcon: ({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />,
    style: { background: token.colorBgContainer }
  }
  const renderCollapse = item => (
    <div className="lim_cardMarBot" key={item.key}>
      <Collapse {...collapseProps} defaultActiveKey={[item.key]} items={item.items} />
    </div>
  )

  return (
    <div className="workflow-common-panel flexCol lim_case caseOverFlowY">
      <span className="lim_title">用于用户输入的意图识别，并将其与预设意图选项进行匹配</span>
      {/* 内容 */}
      {collapseItems.map(renderCollapse)}
      {/* 运行抽屉 */}
      {runDrawerHid && <RunDrawer nodeData={info} openDef={runDrawerHid} setrunDrawerHid={setrunDrawerHid}></RunDrawer>}
    </div>
  )
}

export default React.memo(IntentPanel)
